package com.cheng.system.service.impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cheng.common.constants.RedisKey;
import com.cheng.common.constants.SessionKeys;
import com.cheng.common.utils.WeChatUtils;
import com.cheng.system.model.User;
import com.cheng.system.service.IAuthService;
import com.cheng.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class AuthWechatImpl implements IAuthService<String> {
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    AuthUsernamePasswordImpl authUsernamePassword;

    @Override
    public SaTokenInfo signUp(String openId) throws Throwable {
        User user = new User();
        user.setUserName(RandomUtil.randomString(10));
        user.setNickName(user.getUserName());
        user.setPassword(RandomUtil.randomString(10));
        user.setOpenId(openId);
        return authUsernamePassword.signUp(user);
    }

    @Override
    public SaTokenInfo login(String code) throws Throwable {
        JSONObject session = WeChatUtils.getSession(code);
        String openId = (String) session.get("openid");
        Boolean isSet = redisTemplate.opsForValue().setIfAbsent(RedisKey.LOGIN_KEY + openId, 1, 5, TimeUnit.SECONDS);
        if (!isSet) {
            return null;
        }
        User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getOpenId, openId));
        if (user == null) {
            SaTokenInfo saTokenInfo = signUp(openId);
            StpUtil.login(saTokenInfo.loginId);
        } else {
            StpUtil.login(user.getUserId());
        }
        SaSession saSession = StpUtil.getSession();
        saSession.set(SessionKeys.WECHAT_SESSION, session);
        return StpUtil.getTokenInfo();
    }
}
